package com.school.sports.controller;

import com.school.sports.common.Result;
import com.school.sports.dto.LoginRequest;
import com.school.sports.dto.LoginResponse;
import com.school.sports.exception.BusinessException;
import com.school.sports.service.AuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;


/**
 * 认证控制器
 * 提供用户登录、登出、令牌刷新等功能
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@Tag(name = "认证管理", description = "用户认证相关接口，包括登录、登出、令牌验证等功能")
public class AuthController {

    private final AuthService authService;

    /**
     * 构造函数
     * @param authService 认证服务
     */
    @Autowired
    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    /**
     * 用户登录
     */
    @Operation(summary = "用户登录", description = "用户使用用户名和密码进行登录，成功后返回JWT令牌")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "登录成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "401", description = "用户名或密码错误")
    })
    @PostMapping("/login")
    public Result<LoginResponse> login(
            @Parameter(description = "登录请求信息，包含用户名和密码", required = true)
            @Valid @RequestBody LoginRequest loginRequest) {
        try {
            LoginResponse response = authService.login(loginRequest);
            return Result.success("登录成功", response);
        } catch (Exception e) {
            log.error("登录失败：{}", e.getMessage());
            throw new BusinessException("登录失败：" + e.getMessage());
        }
    }

    /**
     * 用户登出
     */
    @Operation(summary = "用户登出", description = "用户登出系统，使JWT令牌失效")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "登出成功"),
            @ApiResponse(responseCode = "400", description = "令牌无效或已过期")
    })
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            authService.logout(token);
            return Result.success("登出成功");
        } catch (Exception e) {
            log.error("登出失败：{}", e.getMessage());
            throw new BusinessException("登出失败：" + e.getMessage());
        }
    }

    /**
     * 刷新令牌
     */
    @Operation(summary = "刷新令牌", description = "使用当前有效的JWT令牌获取新的令牌")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "令牌刷新成功"),
            @ApiResponse(responseCode = "400", description = "令牌无效或已过期")
    })
    @PostMapping("/refresh")
    public Result<String> refreshToken(
            @Parameter(description = "当前有效的JWT令牌，格式：Bearer <token>", required = true)
            @RequestHeader("Authorization") String token) {
        try {
            String newToken = authService.refreshToken(token);
            return Result.success("令牌刷新成功", newToken);
        } catch (Exception e) {
            log.error("令牌刷新失败：{}", e.getMessage());
            throw new BusinessException("令牌刷新失败：" + e.getMessage());
        }
    }

    /**
     * 验证令牌有效性
     */
    @Operation(summary = "验证令牌", description = "验证JWT令牌是否有效")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "验证完成，返回令牌是否有效"),
            @ApiResponse(responseCode = "400", description = "令牌格式错误")
    })
    @GetMapping("/validate")
    public Result<Boolean> validateToken(
            @Parameter(description = "需要验证的JWT令牌，格式：Bearer <token>", required = true)
            @RequestHeader("Authorization") String token) {
        try {
            // 这里可以添加令牌验证逻辑
            return Result.success(true);
        } catch (Exception e) {
            return Result.success(false);
        }
    }

    /**
     * 检查用户名是否可用
     */
    @Operation(summary = "检查用户名", description = "检查用户名是否已被注册")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "检查完成"),
            @ApiResponse(responseCode = "400", description = "请求参数错误")
    })
    @PostMapping("/check-username")
    public Result<Boolean> checkUsername(
            @Parameter(description = "用户名", required = true)
            @RequestParam String username) {
        try {
            boolean exists = authService.checkUsernameExists(username);
            return Result.success(!exists); // 返回是否可用（true=可用，false=已存在）
        } catch (Exception e) {
            log.error("检查用户名失败：{}", e.getMessage());
            throw new BusinessException("检查用户名失败：" + e.getMessage());
        }
    }

    /**
     * 用户注册
     */
    @Operation(summary = "用户注册", description = "用户注册新账号")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "注册成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "409", description = "用户名已存在")
    })
    @PostMapping("/register")
    public Result<String> register(
            @Parameter(description = "注册信息", required = true)
            @Valid @RequestBody Map<String, Object> registerData) {
        try {
            authService.register(registerData);
            return Result.success("注册成功");
        } catch (Exception e) {
            log.error("用户注册失败：{}", e.getMessage());
            throw new BusinessException("注册失败：" + e.getMessage());
        }
    }

    /**
     * 验证安全问题
     */
    @Operation(summary = "验证安全问题", description = "验证用户安全问题的答案")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "验证完成"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "401", description = "安全问题答案错误")
    })
    @PostMapping("/verify-security-question")
    public Result<Map<String, Object>> verifySecurityQuestion(
            @Parameter(description = "安全问题验证信息", required = true)
            @RequestBody Map<String, Object> verifyData) {
        try {
            Map<String, Object> result = authService.verifySecurityQuestion(verifyData);
            return Result.success("验证成功", result);
        } catch (Exception e) {
            log.error("验证安全问题失败：{}", e.getMessage());
            throw new BusinessException("验证失败：" + e.getMessage());
        }
    }

    /**
     * 重置密码
     */
    @Operation(summary = "重置密码", description = "通过安全问题验证后重置用户密码")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "重置成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "401", description = "验证失败")
    })
    @PostMapping("/reset-password")
    public Result<String> resetPassword(
            @Parameter(description = "密码重置信息", required = true)
            @RequestBody Map<String, Object> resetData) {
        try {
            authService.resetPassword(resetData);
            return Result.success("密码重置成功");
        } catch (Exception e) {
            log.error("密码重置失败：{}", e.getMessage());
            throw new BusinessException("重置失败：" + e.getMessage());
        }
    }
}